// 路由守卫
import router from "@/router";
import nprogress from "nprogress";
import "nprogress/nprogress.css";
import useUserStore from "@/store/modules/user";
import setting from "./setting";
import { ElMessage } from "element-plus";
nprogress.configure({showSpinner: false})
// 路由守卫
router.beforeEach(async (to, from, next) => {
  nprogress.start();
  document.title = setting.title+' - ' + (to.meta.title as string);
  let userStore = useUserStore();
  let username = userStore.username;
  let token = userStore.token;
  if (token) {
    //存在token
    if (to.path == "/login") {
      next({ path: "/" });
    } else {
      if (username) {
        //用户信息已存在
        next();
      } else {//用户信息不存在
        try {
          await userStore.userInfo();//获取用户信息
          next();
        } catch (error) {
          //token失效
          try{
            await userStore.userLogout();//退出登录
          }catch(err:any){
            ElMessage.error(err.message)
          }
          next({ path: "/login", query: { redirect: to.path } });
        }
      }
    }
  } else {
    //未登陆
    if (to.path == "/login") {
      next();
    } else {
      //未登陆且访问的不是登录页
      next({ path: "/login", query: { redirect: to.path } });
    }
  }
});
router.afterEach((to, from) => {
  nprogress.done();
});
